package com.vilen.weixin.controller;

import com.vilen.basic.kit.BasicKit;
import com.vilen.weixin.kit.SecurtiyKit;
import com.vilen.weixin.kit.WeixinMessageKit;
import com.vilen.weixin.web.servlet.WeixinContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * Created by Administrator on 2016/2/14.
 */
@Controller
public class WeixinBasicController {
    //验证token
    @RequestMapping(value = "/wreceive",method = RequestMethod.GET)
    public void handlerGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        /*
        *   signature	微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
            timestamp	时间戳
            nonce	随机数
            echostr	随机字符串
        *
        *
        * */
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        String[] arrs = {WeixinContext.getInstance().getToken(),nonce,timestamp};
        System.out.println(arrs[1]+"---"+arrs[2]);
        StringBuffer sb = new StringBuffer();
        Arrays.sort(arrs);
        for (String a : arrs) {
            sb.append(a);
        }
        String sha1 = SecurtiyKit.sha1(sb.toString());
        //比较是 相同
        System.out.println(sha1);
//        System.out.println(sha1.equals(signature));
        if(sha1.equals(signature)) {
            response.getWriter().println(echostr);
        }
    }
    //消息
    @RequestMapping(value = "/wreceive",method = RequestMethod.POST)
    public void handlerPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/xml;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String rel = WeixinMessageKit.handlerReceiveMsg(request);
        System.out.println("--------rel:"+rel);
        if(!BasicKit.isEmpty(rel)) {
            //有值
            response.getWriter().write(rel);
        }
    }


}
